<template>
  <div class="p-4">
    <a-row :gutter="15">
      <a-col :span="4">
        <dept-search
          ref="deptSearchRef"
          :original="originalTree"
          :data="deptTreeOption"
          :baseFields="replaceFields"
          @select="handleSelect"
        />
      </a-col>
      <a-col :span="20">
        <div class="mb-3">
          <form-search
            :formFields="formFields"
            @search="handleQuery"
            @reset="handleQuery"
          />
        </div>
        <a-row :gutter="10" class="mb-2">
          <a-col v-has-permi="['system:user:add']">
            <a-button color="success" @click="handleAdd">
              {{ t("common.add") }}
            </a-button>
          </a-col>
          <a-col v-has-permi="['system:user:delete']">
            <a-popconfirm
              :title="t('common.confirmDelete')"
              :ok-text="t('common.okText')"
              :cancel-text="t('common.cancelText')"
              @confirm="confirm"
              @cancel="cancel"
            >
              <a-button :disabled="!hasSelected" color="error">
                {{ t("common.delete") }}
              </a-button>
            </a-popconfirm>
          </a-col>
          <!-- <a-col>
            <a-button color="warning">
              {{ t('common.export') }}
            </a-button>
          </a-col> -->
          <!-- <a-col>
            <a-button color="normal">
              {{ t('common.import') }}
            </a-button>
          </a-col> -->
        </a-row>

        <a-table
          :loading="loading"
          rowKey="id"
          :row-selection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
          }"
          :columns="columns"
          :data-source="userList"
          :pagination="pagination"
          @change="handleTableChange"
        >
          <template #department="{ record }">
            <span>
              {{ record.department.deptName }}
            </span>
          </template>
          <template #status="{ record }">
            <span>{{ selectDictLabel(statusOptions, record.status) }}</span>
          </template>
          <template #roles="{ record }">
            <span>{{ getRoles(record) }}</span>
          </template>
          <template #action="{ record }">
            <span>
              <a-button
                type="link"
                color="success"
                class="mr-3"
                @click="handleUpdate(record)"
                v-has-permi="['system:user:update']"
              >
                {{ t("common.update") }}
              </a-button>
              <a-button
                type="link"
                color="success"
                class="mr-3"
                @click="showModal(record)"
                v-has-permi="['system:user:resetPwd']"
              >
                {{ t("routes.user.resetPwd") }}
              </a-button>
              <a-popconfirm
                :title="t('common.confirmDelete')"
                :ok-text="t('common.okText')"
                :cancel-text="t('common.cancelText')"
                @confirm="confirm(record)"
                @cancel="cancel"
              >
                <a-button
                  type="link"
                  color="error"
                  v-has-permi="['system:user:delete']"
                >
                  {{ t("common.delete") }}
                </a-button>
              </a-popconfirm>
            </span>
          </template>
        </a-table>
      </a-col>
    </a-row>

    <!-- 新增修改用户 -->
    <AddOrUpdate @finished="handleFinished" ref="addOrUpdateRef" />
    <!-- 重置密码 -->
    <ResetPwd ref="resetPwdRef" />
  </div>
</template>
<script lang="ts">
import {
  defineComponent,
  reactive,
  ref,
  onMounted,
  toRefs,
  computed,
} from "vue";
import { Row, Col, Popconfirm, Table } from "ant-design-vue";
import { TreeDataItem } from "ant-design-vue/es/tree/Tree";
import { getDict, selectDictLabel } from "@/utils/dictFormat";
import { message as Message } from "ant-design-vue";
import { getDept } from "@/api/admin/system/dept";
import {
  listUser,
  delUser,
  // exportUser,
  // importTemplate,
} from "@/api/admin/system/user";
import { getRole } from "@/api/admin/system/role";
import { handleTree } from "@/utils/tools";
import "vue3-treeselect/dist/vue3-treeselect.css";
import { useUserStore } from "@/store/modules/user";
import { useAppStore } from "@/store/modules/app";
import { TableState } from "ant-design-vue/es/table/interface";

// 组件
import DeptSearch from "@/components/DeptSearch/index.vue";
import FormSearch from "@/components/FormSearch/index.vue";
import AddOrUpdate from "./AddOrUpdate.vue";
import ResetPwd from "./ResetPwd.vue";
import { IUser } from "@/api/admin/system/user/type";
import { IRole } from "@/api/admin/system/role/type";
import { IData } from "@/api/admin/system/dict/data/type";
import { IDept } from "@/api/admin/system/dept/type";
import { useI18n } from "@/hooks/useI18n";

const { t } = useI18n();

type Pagination = TableState["pagination"];

const columns = [
  {
    title: t("routes.user.userName"),
    dataIndex: "userName",
    key: "userName",
    align: "center",
  },
  {
    title: t("routes.user.nickName"),
    dataIndex: "nickName",
    key: "nickName",
    align: "center",
  },
  {
    title: t("routes.user.roleIds"),
    key: "roles",
    align: "center",
    slots: {
      customRender: "roles",
    },
  },
  {
    title: t("routes.user.department"),
    key: "department",
    align: "center",
    slots: {
      customRender: "department",
    },
  },
  {
    title: t("routes.user.mobile"),
    key: "mobile",
    dataIndex: "mobile",
    align: "center",
  },
  {
    title: t("routes.user.status"),
    dataIndex: "status",
    key: "status",
    align: "center",
    slots: { customRender: "status" },
  },
  {
    title: t("routes.user.createdAt"),
    dataIndex: "createdAt",
    key: "createdAt",
    align: "center",
  },
  {
    title: t("routes.user.action"),
    key: "action",
    align: "center",
    slots: { customRender: "action" },
  },
];

export default defineComponent({
  name: "User",
  components: {
    "a-row": Row,
    "a-col": Col,
    "a-popconfirm": Popconfirm,
    "a-table": Table,
    DeptSearch,
    FormSearch,
    AddOrUpdate,
    ResetPwd,
  },
  setup() {
    const userStore = useUserStore();
    const loading = computed(() => useAppStore().loading);
    const roleOptions = ref<IRole[]>([]);
    const statusOptions = ref<IData[]>([]);
    /**
     * 左侧树形控件操作
     */
    const deptSearchRef = ref();
    const originalTree = ref<IDept[]>([]);
    const replaceFields = {
      children: "children",
      title: "deptName",
      key: "deptId",
    };
    const deptTreeOption = ref<TreeDataItem[]>([]);
    const handleSelect = (keys: number[]) => {
      queryParams.deptId = keys[0];
      handleQuery(queryParams);
    };

    // 查询表单操作
    const queryParams = reactive({
      userName: undefined || "",
      deptId: 0,
      roleId: undefined || "",
      pageNum: 1,
      pageSize: 10,
    });
    const formFields = reactive([
      {
        type: "input",
        label: t("routes.user.userName"),
        name: "userName",
        value: undefined,
        placeholder: t("routes.user.userNamePlaceholder"),
      },
      {
        type: "select",
        label: t("routes.user.roleIds"),
        name: "roleId",
        value: undefined,
        placeholder: t("routes.user.roleIdsPlaceholder"),
        normalizer: {
          value: "id",
          label: "roleName",
        },
        options: roleOptions,
      },
    ]);

    const handleQuery = (query: { userName: string; roleId: string }) => {
      pagination.value.current = 1;
      queryParams.pageNum = pagination.value.current;
      queryParams.userName = query.userName;
      queryParams.roleId = query.roleId;
      getList(queryParams);
    };

    /**
     * 表格操作
     */
    const state = reactive({
      selectedRowKeys: [],
    });
    const userList = ref<IUser[]>([]);
    const pagination = ref({
      total: 0,
      current: 1,
      pageSize: 10,
      showSizeChanger: true,
      showTotal: (total) => `共 ${total} 条`,
    });

    const handleTableChange = (page: Pagination) => {
      (pagination.value as Pagination) = page;
      queryParams.pageNum = pagination.value.current;
      queryParams.pageSize = pagination.value.pageSize;
      getList(queryParams);
    };
    // 判断删除按钮是否可点击
    const hasSelected = computed(() => state.selectedRowKeys.length > 0);
    // 多选框选择操作
    const onSelectChange = (selectedRowKeys) => {
      state.selectedRowKeys = selectedRowKeys;
    };

    // 格式角色
    const getRoles = (record) => {
      return record.roles.map((list) => list.roleName).join(",");
    };

    // 部门树选项
    const deptOptions = ref<IDept[]>([]);
    // 获取部门数据
    const getDeptList = () => {
      getDept().then((res) => {
        originalTree.value = res.data.rows;
        deptTreeOption.value = handleTree(
          res.data.rows,
          "deptId",
          "parentId",
          "children",
          0
        ).tree;
        deptSearchRef.value.expandedKeys.value = originalTree.value.map(
          (item: TreeDataItem) => item.id
        );
      });
    };
    const addOrUpdateRef = ref();

    // 完成表单提交回调
    const handleFinished = () => {
      getList(queryParams);
    };

    // 新增按钮操作
    const handleAdd = () => {
      addOrUpdateRef.value.handleShow();
    };

    // 更新按钮操作
    const handleUpdate = (row) => {
      addOrUpdateRef.value.handleShow(row);
    };

    // 确认删除
    const confirm = (row) => {
      const ids = row.id || state.selectedRowKeys;
      console.log(ids);
      delUser(ids).then(() => {
        if (
          (ids.length && ids.length === userList.value.length) ||
          userList.value.length === 1
        ) {
          if (
            Math.ceil(pagination.value.total / queryParams.pageSize) ===
              queryParams.pageNum &&
            queryParams.pageNum > 1
          ) {
            queryParams.pageNum--;
          }
        }
        getList(queryParams);
        Message.success(t("common.deleteSuccess"));
      });
    };
    // 取消删除
    const cancel = (e: MouseEvent) => {
      console.log(e);
      Message.success(t("common.cancelDelete"));
    };

    // 获取表格数据
    const getList = (queryParams?: {}) => {
      listUser(queryParams).then((res) => {
        userList.value = res.data.rows;
        pagination.value.total = res.data.count;
      });

      getDept().then((res) => {
        // 获取菜单树
        const children = handleTree(
          res.data.rows,
          "deptId",
          "parentId",
          "children",
          userStore.userInfo.deptId
        ).tree;
        const parent = res.data.rows.filter(
          (item) => item.deptId === userStore.userInfo.deptId
        );
        parent[0].children = children;
        deptOptions.value = parent;
        console.log(deptOptions);
      });
    };

    /**
     * 重置密码操作
     */
    const resetPwdRef = ref();
    const showModal = (row) => {
      resetPwdRef.value.showModal(row);
    };

    const init = () => {
      getDeptList();
      getList(queryParams);
      getRole().then((res) => {
        roleOptions.value = res.data.rows;
      });
    };

    onMounted(async () => {
      statusOptions.value = await getDict("sys_normal_disable");
      init();
    });

    return {
      t,
      loading,
      replaceFields,
      deptSearchRef,
      originalTree,
      deptTreeOption,
      handleSelect,

      formFields,
      handleQuery,

      statusOptions,
      columns,
      ...toRefs(state),
      userList,
      pagination,
      handleTableChange,
      selectDictLabel,
      hasSelected,
      onSelectChange,
      getRoles,
      confirm,
      cancel,
      handleAdd,
      handleUpdate,

      addOrUpdateRef,
      handleFinished,

      resetPwdRef,
      showModal,
    };
  },
});
</script>
